package com.ruoyi.web.controller.system;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysApp;
import com.ruoyi.system.service.ISysAppService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 系统应用Controller
 * 
 * @author ning
 * @date 2024-06-25
 */
@RestController
@RequestMapping("/system/app")
public class SysAppController extends BaseController
{
    @Autowired
    private ISysAppService sysAppService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 查询系统应用列表
     */
    @PreAuthorize("@ss.hasPermi('system:app:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysApp sysApp)
    {
        startPage();
        List<SysApp> list = sysAppService.selectSysAppList(sysApp);
        return getDataTable(list);
    }

    /**
     * 查询系统启用的全部应用
     */
    @GetMapping("/enableList")
    public AjaxResult enableList(SysApp sysApp)
    {
        List<SysApp> list = sysAppService.selectSysAppList(sysApp);
        return success(list);
    }

    /**
     * 查询用户拥有并启用的应用
     */
    @GetMapping("/getUserEnableList")
    public AjaxResult getUserEnableList()
    {
        SysApp sysApp = new SysApp();
        sysApp.setStatusFlag(2);
        // 获取启用的全部应用
        List<SysApp> list = sysAppService.selectSysAppList(sysApp);
        Long userId = SecurityUtils.getUserId();
        // 获取用户的菜单
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        List<SysApp> UserAppList = new ArrayList<>();
        List<Map> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(menus)&&!CollectionUtils.isEmpty(list)){
            // 将用户菜单按所属应用分组
            Map<String, List<SysMenu>> listMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getAppCode));
            // 将全部应用转为应用编码和对应应用的map
            Map<String, SysApp> appMap = list.stream().collect(Collectors.toMap(SysApp::getAppCode, app ->app));
            // 遍历用户拥有的应用并从全部应用中根据应用编码取出对应应用
            for (String key : listMap.keySet()) {
                SysApp app = appMap.get(key);
                if (!ObjectUtils.isEmpty(app)){
                    UserAppList.add(app);
                }
            }
            // 将list中元素顺序反转
            Collections.reverse(UserAppList);
            // 将用户拥有的应用组装为应用分类对应应用的list
            Map<String, List<SysApp>> appTypeList = UserAppList.stream().collect(Collectors.groupingBy(SysApp::getAppTypeName));
            for (String key : appTypeList.keySet()) {
                Map<String,Object> enableAppMap = new HashMap();
                //按排序正序排(从小到大)
                List<SysApp> sysAppList = appTypeList.get(key);
                sysAppList.sort(Comparator.comparing(SysApp::getAppSort));
                enableAppMap.put("appTypeName",key);
                enableAppMap.put("appList",sysAppList);
                result.add(enableAppMap);
            }
        }
        return success(result);
    }

    /**
     * 查询用户拥有并启用的应用(未按应用分类进行分组，用于工作台显示)
     */
    @GetMapping("/getUserEnableListWorkbench")
    public AjaxResult getUserEnableListWorkbench()
    {
        SysApp sysApp = new SysApp();
        sysApp.setStatusFlag(2);
        // 获取启用的全部应用
        List<SysApp> list = sysAppService.selectSysAppList(sysApp);
        Long userId = SecurityUtils.getUserId();
        // 获取用户的菜单
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        List<SysApp> UserAppList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(menus)&&!CollectionUtils.isEmpty(list)){
            // 将用户菜单按所属应用分组
            Map<String, List<SysMenu>> listMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getAppCode));
            // 将全部应用转为应用编码和对应应用的map
            Map<String, SysApp> appMap = list.stream().collect(Collectors.toMap(SysApp::getAppCode, app ->app));
            // 遍历用户拥有的应用并从全部应用中根据应用编码取出对应应用
            for (String key : listMap.keySet()) {
                SysApp app = appMap.get(key);
                if (!ObjectUtils.isEmpty(app)){
                    UserAppList.add(app);
                }
            }
            //UserAppList按appSort排序
            UserAppList.sort(Comparator.comparing(SysApp::getAppSort));
        }
        return success(UserAppList);
    }

    /**
     * 导出系统应用列表
     */
    @PreAuthorize("@ss.hasPermi('system:app:export')")
    @Log(title = "系统应用", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysApp sysApp)
    {
        List<SysApp> list = sysAppService.selectSysAppList(sysApp);
        ExcelUtil<SysApp> util = new ExcelUtil<SysApp>(SysApp.class);
        util.exportExcel(response, list, "系统应用数据");
    }

    /**
     * 获取系统应用详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:app:query')")
    @GetMapping(value = "/{appId}")
    public AjaxResult getInfo(@PathVariable("appId") Long appId)
    {
        return success(sysAppService.selectSysAppByAppId(appId));
    }

    /**
     * 新增系统应用
     */
    @PreAuthorize("@ss.hasPermi('system:app:add')")
    @Log(title = "系统应用", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysApp sysApp)
    {
        sysApp.setCreateBy(getUsername());
        return toAjax(sysAppService.insertSysApp(sysApp));
    }

    /**
     * 修改系统应用
     */
    @PreAuthorize("@ss.hasPermi('system:app:edit')")
    @Log(title = "系统应用", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysApp sysApp)
    {
        sysApp.setUpdateBy(getUsername());
        return toAjax(sysAppService.updateSysApp(sysApp));
    }

    /**
     * 删除系统应用
     */
    @PreAuthorize("@ss.hasPermi('system:app:remove')")
    @Log(title = "系统应用", businessType = BusinessType.DELETE)
	@DeleteMapping("/{appIds}")
    public AjaxResult remove(@PathVariable Long[] appIds)
    {
        return toAjax(sysAppService.deleteSysAppByAppIds(appIds));
    }
}
